//
//  ResultsViewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/8/5.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit

class ResultsViewController: UIViewController {
    var filterview:FilterView!
    var popview:ZXPopView!
    var pageNo=1
    var dataSource:mSearchResult!
    var productList = [mSearchProduct]()
    var keywords:String!=""
    var cid:String!=""
    var b_id:String!=""
    var orderKey:String!="1"
    var orderType:String!="1"
    var sid:String!=""
    @IBOutlet weak var uv_back: UIView!
    @IBOutlet weak var uv_search: UIView!
    @IBOutlet weak var lb_keywords: UILabel!
    
    @IBOutlet weak var lb_default: UILabel!
    @IBOutlet weak var lb_price: UILabel!
    @IBOutlet weak var lb_salecount: UILabel!
    @IBOutlet weak var lb_filter: UILabel!
    @IBOutlet weak var tableview: UITableView!
    init(keywords:String,cid:String){
        super.init(nibName: nil, bundle: nil)
        self.keywords=keywords
        self.cid=cid
        loaddata(keywords: keywords, cid: cid, b_id: b_id, orderKey: orderKey, orderType: orderType, sid: sid)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        lb_keywords.text=keywords
        uv_search.layer.cornerRadius=5
        uv_back.addOnClickListener(target: self, action: #selector(back))
        uv_search.addOnClickListener(target: self, action: #selector(back))
        
        lb_default.addOnClickListener(target: self, action: #selector(reloadByDefault))
        lb_price.addOnClickListener(target: self, action: #selector(reloadByPrice))
        lb_salecount.addOnClickListener(target: self, action: #selector(reloadBySaleCount))
        lb_filter.addOnClickListener(target: self, action: #selector(filter))
        
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        tableview.register(UINib(nibName: "ResultTableViewCell", bundle: nil), forCellReuseIdentifier: "re")
        tableview.separatorStyle = .none
        
        let footer = TTRefreshFooter  {  [weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = strongSelf.pageNo + 1
            strongSelf.loaddata(keywords: strongSelf.keywords, cid: strongSelf.cid, b_id: strongSelf.b_id, orderKey: strongSelf.orderKey, orderType: strongSelf.orderType, sid: strongSelf.sid);
        }
        
        tableview.mj_footer = footer
        tableview.mj_footer.isHidden = true
        // Do any additional setup after loading the view.
    }
    @objc func back(){
        self.navigationController?.popViewController(animated: false)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    
    @objc func reloadByDefault(){//综合orderkey=1
        lb_default.textColor = .red
        lb_price.textColor = .black
        lb_salecount.textColor = .black
        lb_filter.textColor = .black
        
        pageNo=1
        orderKey="1"
        if orderType=="1"{
            orderType="2"
        }else{
            orderType="1"
        }
        loaddata(keywords: keywords, cid: cid, b_id: b_id, orderKey: orderKey, orderType: orderType, sid: sid)
    }
    @objc func reloadByPrice(){//价格orderkey=3
        lb_default.textColor = .black
        lb_price.textColor = .red
        lb_salecount.textColor = .black
        lb_filter.textColor = .black
        
        pageNo=1
        orderKey="3"
        if orderType=="1"{
            orderType="2"
        }else{
            orderType="1"
        }
        loaddata(keywords: keywords, cid: cid, b_id: b_id, orderKey: orderKey, orderType: orderType, sid: sid)
    }
    @objc func reloadBySaleCount(){//销量orderkey=2
        lb_default.textColor = .black
        lb_price.textColor = .black
        lb_salecount.textColor = .red
        lb_filter.textColor = .black
        
        pageNo=1
        orderKey="2"
        if orderType=="1"{
            orderType="2"
        }else{
            orderType="1"
        }
        loaddata(keywords: keywords, cid: cid, b_id: b_id, orderKey: orderKey, orderType: orderType, sid: sid)
    }
    @objc func filter(){//筛选
        if popview==nil{
            popview = ZXPopView.init(frame: self.view.bounds)
            filterview=Bundle.main.loadNibNamed("FilterView", owner: nil, options: nil)?[0]as!FilterView
            filterview.btn_reset.layer.cornerRadius=10
            filterview.btn_reset.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMinXMinYCorner.rawValue|CACornerMask.layerMinXMaxYCorner.rawValue)
            filterview.btn_confirm.layer.cornerRadius=10
            filterview.btn_confirm.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMaxXMinYCorner.rawValue|CACornerMask.layerMaxXMaxYCorner.rawValue)
            filterview.btn_reset.addOnClickListener(target: self, action: #selector(reset))
            filterview.btn_confirm.addOnClickListener(target: self, action: #selector(confirm))
            
            filterview.loadData(keyword: keywords, cid: cid, a_id: sid, b_id: b_id)
            filterview.collectionview.delegate=filterview
            filterview.collectionview.dataSource=filterview
            filterview.collectionview.register(UINib(nibName: "FilterCell", bundle: nil), forCellWithReuseIdentifier: "re")
            filterview.collectionview.register(UINib(nibName: "FilterHeadView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "head")
            
            filterview.block = {b_id,c_id,s_id in
                print(b_id)
                print(c_id)
                print(s_id)
                self.cid=c_id
                self.b_id=b_id
                self.sid=s_id
                self.loaddata(keywords: self.keywords, cid: self.cid, b_id: self.b_id, orderKey: self.orderKey, orderType: self.orderType, sid: self.sid)
            }
            
            popview.contenView = filterview
            popview.anim = 2
            filterview.snp.makeConstraints { (make) in
                make.right.equalTo(0)
                make.width.equalTo(screenW/4*3)
                make.height.equalTo(screenH)
            }
            popview.rightToLeft(view: self.view)
        }else{
            popview.rightToLeft(view: self.view)
        }
        
    }
    @objc func reset(){
        filterview.loadData(keyword: keywords, cid: cid, a_id: sid, b_id: b_id)
    }
    @objc func confirm(){
        popview.leftToRight()
    }
    
    /* @param cid          分类ID
     * @param b_id         品牌ID
     * @param orderKey     排序项（1：默认，2：销量，3：价格，4：评论数，5：上架时间）
     * @param orderType    排序方式（1：升序，2：降序）
     */
    func loaddata(keywords:String,cid:String,b_id:String,orderKey:String,orderType:String,sid:String){
        var d = ["app_key":app_key,
                 "keywords":keywords,
                 "orderKey":orderKey,
                 "orderType":orderType,
                 "pageNo":String(pageNo),
                 "pageSize":"20",
                 "timestamp":getTimestamp()
            ] as [String : String]
        if cid != ""{
            d["cid"]=cid
        }
        if b_id != ""{
            d["b_id"]=b_id
        }
        if sid != ""{
            d["sid"]=sid
        }
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        
        AlamofireHelper.get(url: GetSearchProducts, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.pageNo == 1{ ss.productList.removeAll()}
            
            if ss.tableview.mj_footer.isRefreshing() {
                ss.tableview.mj_footer.endRefreshing()
                
            }
            ss.dataSource=mSearchResult.init(json: res)
            
            if ss.dataSource.Product.count>0 {
                if ss.tableview.mj_footer.isHidden && ss.dataSource.Product.count > 0 {
                    ss.tableview.mj_footer.isHidden = false
                }
                ss.productList.insert(contentsOf: ss.dataSource.Product, at: ss.productList.count)
                if ss.productList.count < 20 {
                    ss.tableview.mj_footer.state = .noMoreData
                }
            }else {
                ss.tableview.mj_footer.state = .noMoreData
            }
            
            ss.tableview.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.tableview.mj_footer.isRefreshing() {ss.tableview.mj_footer.endRefreshing()}
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
}
extension ResultsViewController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return productList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "re") as!ResultTableViewCell
        let item=productList[indexPath.row]
        cell.icon.setImage(path: URL.init(string: item.ImagePath!)!)
        cell.name.text=item.ProductName
        var str=""
        for index in 0..<(item.ProductAttributeInfos.count>3 ? 3 : item.ProductAttributeInfos.count){
            str+=item.ProductAttributeInfos[index]+"|"
        }
        cell.label.text=str.count>0 ? str.prefix(str.count-1).description : ""
        cell.price.text="￥\(item.SalePrice)"
        cell.count.text="\(item.SaleCount)人付款"
        cell.addr.text=item.ProductAddress
        cell.shopname.text=item.ShopName
        
        cell.seven_day.backgroundColor = "#EEF1F1".color()
        cell.seven_day.layer.cornerRadius=2
        cell.seven_day.clipsToBounds=true
        
        cell.safe.backgroundColor = "#EEF1F1".color()
        cell.safe.layer.cornerRadius=2
        cell.safe.clipsToBounds=true
        
        if item.ShopName=="官方自营店"{
            cell.name.text="           \(item.ProductName!)"
            cell.lb_pre.isHidden=false
            cell.lb_pre.text="官方"
            cell.lb_pre.backgroundColor=UIColor.red
            cell.lb_pre.textColor=UIColor.white
            cell.lb_pre.font=UIFont.systemFont(ofSize: 12)
            cell.lb_pre.paddingLeft=5
            cell.lb_pre.paddingRight=5
            cell.lb_pre.layer.cornerRadius=5
            cell.lb_pre.clipsToBounds=true
        }else{
            cell.name.text=item.ProductName
            cell.lb_pre.isHidden=true
        }
        
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.navigationController?.pushViewController(ProductDetailViewController(pid: String(productList[indexPath.row].ProductId)), animated: true)
    }
    
}
